package solutions;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-27
 * Time: 13:17
 */


//https://leetcode.cn/problems/linked-list-cycle-ii/submissions/397312451/
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        ListNode dummyHead = head;
        ListNode curr = null;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                curr = slow;
                break;
            }
        }
        if (curr == null) {
            return null;
        }
        while (dummyHead != curr) {
            dummyHead = dummyHead.next;
            curr = curr.next;
        }
        return curr;
    }
}
